using System;
using Behaving.Actions;

namespace Behaving.Composites
{
    public class Conditional : Composite
    {
        private readonly Func<bool> _canRun;

        public Conditional(Func<bool> canRun, Behaviour behaviour, Behaviour elseBehaviour = null)
            : base(new[] { behaviour, elseBehaviour })
        {
            _canRun = canRun;
        }

        public Conditional(Func<bool> canRun, Action action, Action elseAction = null)
            : this(canRun, new ActionBehaviour(action), elseAction != null ? new ActionBehaviour(elseAction) : null)
        {
            _canRun = canRun;
        }

        public override RunningState Execute(BehaviourTree behaviourTree)
        {
            if (_canRun())
            {
                return Children[0].Tick(behaviourTree);
            }

            if (Children.Count > 1)
            {
                return Children[1].Tick(behaviourTree);
            }

            return RunningState.Failure;
        }
    }
}